package com.md.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author 刘骄阳
 * 2024-10-18 18:41
 */
public class ChartConverter {
  public static void main(String[] args) {
    String excelFilePath = "D://TK bottle 阻隔性测试报告 Lab trial report.xlsx"; // 替换为您的Excel文件路径

    try (FileInputStream fis = new FileInputStream(excelFilePath);
         Workbook workbook = new XSSFWorkbook(fis)) {
      XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(0); // 获取第一个工作表

      // 提取图表数据
      CategoryDataset dataset = extractChartData(sheet);

      // 创建JFreeChart图表
      JFreeChart chart = createJFreeChart(dataset);

      // 导出图表为PNG文件
      exportChartAsPNG(chart, "output_chart.png");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private static CategoryDataset extractChartData(XSSFSheet sheet) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    // 假设您的数据在工作表的前两列，您需要根据实际数据结构进行修改
    for (Row row : sheet) {
      Cell categoryCell = row.getCell(0); // 类别列
      Cell valueCell = row.getCell(1);     // 值列

      if (categoryCell != null && valueCell != null) {
        String category = categoryCell.getStringCellValue();
        double value = valueCell.getNumericCellValue();

        dataset.addValue(value, "Series1", category);
      }
    }

    return dataset;
  }

  private static JFreeChart createJFreeChart(CategoryDataset dataset) {
    return ChartFactory.createBarChart(
      "Converted Chart",   // 图表标题
      "Category",          // X轴标签
      "Value",             // Y轴标签
      dataset              // 数据集
    );
  }

  private static void exportChartAsPNG(final JFreeChart chart, final String filePath) {
    File chartFile = new File(filePath);
    try {
      ChartUtils.saveChartAsPNG(chartFile, chart, 600, 400);
      System.out.println("图表已保存为: " + chartFile.getAbsolutePath());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
